package com.rightsidetech.http.controller.admin.statis;

import com.github.pagehelper.PageInfo;
import com.rightsidetech.activity.dto.request.ActCouponStatisReq;
import com.rightsidetech.activity.entity.ActCouponActivity;
import com.rightsidetech.activity.entity.ActCouponActivityStatis;
import com.rightsidetech.activity.service.ActCouponService;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.http.aspect.Auth;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.system.dtos.response.store.SysStoreOrderDetailResp;
import com.rightsidetech.system.entity.SysUserLoginInfo;
import com.rightsidetech.system.service.SysAgentInfoService;
import com.rightsidetech.system.service.SysStoreInfoService;
import com.rightsidetech.system.service.SysUserLoginInfoService;
import com.rightsidetech.trade.dtos.request.TdOrderSalesVolumeDayStatisReq;
import com.rightsidetech.trade.dtos.request.TdStatisReq;
import com.rightsidetech.trade.dtos.request.TdStatisTimeReq;
import com.rightsidetech.trade.dtos.response.TdCouponSumAmountStatis;
import com.rightsidetech.trade.dtos.response.TdOrderIncomeRefundDayStatisResp;
import com.rightsidetech.trade.dtos.response.TdOrderSalesVolumeDayStatisResp;
import com.rightsidetech.trade.entity.TdOrderIncomeSalesDayStatis;
import com.rightsidetech.trade.service.TdStatisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/admin/statis")
@ShenyuSpringMvcClient(path = "/admin/statis/**")
@Api(tags = "admin:统计相关")
public class SysStatisController extends BaseController {

    @Resource
    private TdStatisService tdStatisService;
    @Resource
    private SysStoreInfoService sysStoreInfoService;
    @Resource
    private SysAgentInfoService sysAgentInfoService;
    @Resource
    private SysUserLoginInfoService sysUserLoginInfoService;
    @Resource
    private ActCouponService actCouponService;

    @Log
    @Token
    @ApiOperation("用户销量报表 列表")
    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/orderSalesVolumeDayPage")
    public ResponseData<PageInfo<TdOrderSalesVolumeDayStatisResp>> orderSalesVolumeDayStatisPage(TdOrderSalesVolumeDayStatisReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(Long.parseLong(getAttribute()));
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
            req.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        return tdStatisService.orderSalesVolumeDayStatisPage(req);
    }


    @Log
    @Token
    @ApiOperation("用户财务报表 列表")
    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/orderIncomeRefundDayPage")
    public ResponseData<PageInfo<TdOrderIncomeRefundDayStatisResp>> orderIncomeRefundDayStatisPage(TdOrderSalesVolumeDayStatisReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(Long.parseLong(getAttribute()));
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
            req.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        return tdStatisService.orderIncomeRefundDayStatisPage(req);
    }

    @Log
    @Token
    @ApiOperation("统计销量(不传门店默认所有门店)-手动统计")
    //@Auth(bizType = Auth.OPERATOR)
    @PostMapping("/statisSalesVolume")
    public ResponseData statisOrderSalesVolumeDay(@RequestBody TdStatisReq req){
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        //判断门店id是否为空
        if(StringUtils.isEmpty(req.getStoreId())){
            String statisTime = req.getStatisTime();

            List<Long> storeIds = tdStatisService.statisOrderSalesVolumeDayByStatis(statisTime);

            if (!storeIds.isEmpty()) {
                for (Long storeId : storeIds) {
                    SysStoreOrderDetailResp storeDetail = sysStoreInfoService.findStoreByStoreId(storeId);
                    if(StringUtils.isEmpty(storeDetail)){
                        continue;
                    }
                    TdOrderIncomeSalesDayStatis tdStatis = new TdOrderIncomeSalesDayStatis();
                    tdStatis.setStoreInfoId(storeDetail.getStoreId());
                    tdStatis.setStoreName(storeDetail.getStoreName());

                    tdStatis.setAgentInfoId(storeDetail.getAgentId());
                    tdStatis.setAgentName(storeDetail.getAgentName());

                    tdStatis.setAreaId(storeDetail.getAreaId());
                    tdStatis.setAreaName(storeDetail.getAreaName());


                    tdStatisService.statisOrderSalesVolumeDay(statisTime, tdStatis);

                }
            }
            return ResponseData.success();

        }else{
            SysStoreOrderDetailResp storeInfoResp = sysStoreInfoService.findOrderDetailByStoreId(req.getStoreId());
            if(StringUtils.isEmpty(storeInfoResp)){
                return ResponseData.fail(CodeIdEnum.NonStoreInfo);
            }
            TdOrderIncomeSalesDayStatis tdStatis = new TdOrderIncomeSalesDayStatis();
            tdStatis.setStoreInfoId(storeInfoResp.getStoreId());
            tdStatis.setStoreName(storeInfoResp.getStoreName());

            tdStatis.setAgentInfoId(storeInfoResp.getAgentId());
            tdStatis.setAgentName(storeInfoResp.getAgentName());

            tdStatis.setAreaId(storeInfoResp.getAreaId());
            tdStatis.setAreaName(storeInfoResp.getAreaName());

            //判断这天是否有销量统计
            return tdStatisService.statisOrderSalesVolumeDay(req.getStatisTime(),tdStatis);
        }


    }

    @Log
    @Token
    @ApiOperation("统计财务报表(不传门店默认所有门店)- 手动统计")
    //@Auth(bizType = Auth.OPERATOR)
    @PostMapping("/statisIncomeRefund")
    public ResponseData statisIncomeRefund(@RequestBody TdStatisReq req){
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        if(StringUtils.isEmpty(req.getStoreId())){
            String statisTime = req.getStatisTime();

            List<Long> storeIds = tdStatisService.statisOrderSalesVolumeDayByStatis(statisTime);

            if (!storeIds.isEmpty()) {
                for (Long storeId : storeIds) {
                    SysStoreOrderDetailResp storeDetail = sysStoreInfoService.findStoreByStoreId(storeId);
                    if(StringUtils.isEmpty(storeDetail)){
                        continue;
                    }
                    TdOrderIncomeSalesDayStatis tdStatis = new TdOrderIncomeSalesDayStatis();
                    tdStatis.setStoreInfoId(storeDetail.getStoreId());
                    tdStatis.setStoreName(storeDetail.getStoreName());

                    tdStatis.setAgentInfoId(storeDetail.getAgentId());
                    tdStatis.setAgentName(storeDetail.getAgentName());

                    tdStatis.setAreaId(storeDetail.getAreaId());
                    tdStatis.setAreaName(storeDetail.getAreaName());


                    tdStatisService.statisIncomeRefundDay(statisTime, tdStatis);

                }
            }
            return ResponseData.success();

        }else{
            SysStoreOrderDetailResp storeInfoResp = sysStoreInfoService.findOrderDetailByStoreId(req.getStoreId());
            if(StringUtils.isEmpty(storeInfoResp)){
                return ResponseData.fail(CodeIdEnum.NonStoreInfo);
            }
            TdOrderIncomeSalesDayStatis tdStatis = new TdOrderIncomeSalesDayStatis();
            tdStatis.setStoreInfoId(storeInfoResp.getStoreId());
            tdStatis.setStoreName(storeInfoResp.getStoreName());

            tdStatis.setAgentInfoId(storeInfoResp.getAgentId());
            tdStatis.setAgentName(storeInfoResp.getAgentName());

            tdStatis.setAreaId(storeInfoResp.getAreaId());
            tdStatis.setAreaName(storeInfoResp.getAreaName());

            return tdStatisService.statisIncomeRefundDay(req.getStatisTime(),tdStatis);
        }


    }


    @Log
    @Token
    @ApiOperation("手动统计所有门店")
    @PostMapping("/statisAllStore")
    public ResponseData statisAllStore(@RequestBody TdStatisTimeReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        String statisTime = req.getStatisTime();

        List<Long> storeIds = tdStatisService.statisOrderSalesVolumeDayByStatis(statisTime);

        if (!storeIds.isEmpty()) {
            for (Long storeId : storeIds) {
                SysStoreOrderDetailResp storeDetail = sysStoreInfoService.findStoreByStoreId(storeId);
                if(StringUtils.isEmpty(storeDetail)){
                    continue;
                }
                TdOrderIncomeSalesDayStatis tdStatis = new TdOrderIncomeSalesDayStatis();
                tdStatis.setStoreInfoId(storeDetail.getStoreId());
                tdStatis.setStoreName(storeDetail.getStoreName());

                tdStatis.setAgentInfoId(storeDetail.getAgentId());
                tdStatis.setAgentName(storeDetail.getAgentName());

                tdStatis.setAreaId(storeDetail.getAreaId());
                tdStatis.setAreaName(storeDetail.getAreaName());


                tdStatisService.statisOrderSalesVolumeDay(statisTime, tdStatis);
                tdStatisService.statisIncomeRefundDay(statisTime, tdStatis);

            }
        }
        return ResponseData.success();
    }


    @Log
    @Token
    @ApiOperation("手动统计优惠券,不传参数查没有统计过的已结束的优惠券")
    @PostMapping("/statisCoupon")
    public ResponseData statisActCoupon(@RequestBody ActCouponStatisReq req){
        List<Long> activityList = new ArrayList<>();
        //判断是否传入优惠券id
        if(!StringUtils.isEmpty(req.getActivityId())){
            ActCouponActivity activity = actCouponService.findByid(req.getActivityId());
            activityList.add(activity.getId());
        }else{
            //没有则去查询活动结束,并且没有被统计过的优惠券活动
            activityList = actCouponService.findStatisActivityId();
        }

        if(activityList.isEmpty()){
            return ResponseData.fail("没有找到可以统计的优惠活动");
        }

        for(Long activityId:activityList){
            ActCouponActivityStatis statis = new ActCouponActivityStatis();
            //统计优惠券活动
            ActCouponActivity activity2 = actCouponService.getActivityByActivityId(activityId);
            //查找已被使用的优惠券
            Long getCountNum = actCouponService.findCountByActivityId(activityId,(byte) 0);
            //已使用的优惠券
            Long usedCountNum = actCouponService.findCountByActivityId(activityId,(byte) 1);
            //统计金额
            TdCouponSumAmountStatis amountStatis = tdStatisService.statisTotalAmountByActivityId(activityId);

            statis.setReceiveNum(getCountNum + usedCountNum);
            statis.setUseNum(usedCountNum);
            statis.setCouponActivityId(activityId);
            statis.setQuantity(activity2.getTotalQuantity());
            statis.setStatisAt(new Date());
            statis.setTotalPayableAmount(amountStatis.getTotalAmount());
            statis.setTotalPayAmount(amountStatis.getActualAmount());
            statis.setTotalDiscountAmount(amountStatis.getDiscountAmount());

            actCouponService.saveActivityStatis(statis);
        }

        return ResponseData.success();
    }
}
